// 处理路由变化
import { importHtml } from './improt-html'
import { getApps } from './index'
import { getNextRoute, getPrevRoute } from './rewrite-router'
import cssSandbox from './css-sandbox'
import jsSandbox from './js-sandbox'

let prevApp = null
let currentApp = null

export const handleRouter = async () => {
    const apps = getApps()
    const app = apps.find(item => window.location.pathname.startsWith(item.activeRule))

    // 如果切换到了相同的应用，直接返回
    if (currentApp === app) {
        return
    }

    // 卸载当前应用
    if (prevApp) {
        // 清理沙箱环境
        jsSandbox.deactive(prevApp.name)
        cssSandbox.removeShadowContainer(prevApp.name)
        if (prevApp.unmount) {
            await unmount(prevApp)
        }
    }

    if (!app) {
        prevApp = null
        currentApp = null
        return
    }

    // 加载新应用
    const { template, getExternalScripts, exeScripts, styles } = await importHtml(app.entry)
    const container = document.querySelector(app.container)
    if (!container) {
        return
    }

    container.innerHTML = ''

    // 处理样式隔离，创建 Shadow DOM
    const shadowRoot = cssSandbox.processCSS(app.name, styles, container)

    // 将模板添加到 Shadow DOM 中
    const appContent = document.createElement('div')
    appContent.innerHTML = template.innerHTML
    shadowRoot.appendChild(appContent)

    // 激活JS沙箱
    jsSandbox.active(app.name)

    // 配置全局环境变量
    window.__POWERED_BY_QIANKUN__ = true
    window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ = sandbox.proxy

    const appExports = await exeScripts()
    
    // 保存生命周期方法
    app.bootstrap = appExports.bootstrap
    app.mount = appExports.mount
    app.unmount = appExports.unmount

    await bootstrap(app)
    await mount(app)

    // 更新应用状态
    prevApp = app
    currentApp = app
}

async function bootstrap(app) {
    app.bootstrap && (await app.bootstrap())
}

async function mount(app) {
    app.mount && (await app.mount({
        container: cssSandbox.getShadowRoot(app.name)
    }))
}

async function unmount(app) {
    try {
        app.unmount && (await app.unmount({
            container: cssSandbox.getShadowRoot(app.name)
        }))
    } catch (error) {
        console.warn('Unmount error:', error)
    }
}